//
//  HMOAuthViewController.swift
//  SinaWeiBo
//
//  Created by immncjykeny on 2017/5/6.
//  Copyright © 2017年 immncjykeny. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMOAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    
    override func loadView() {
        super.loadView()
        view = webView
        view.backgroundColor = UIColor.white
        //关闭webview的滚动
        webView.scrollView.isScrollEnabled = false
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, action: #selector(close), target: self, isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, action: #selector(autoFill), target: self)
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权页面
       let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(HMAppKey)&redirect_uri=\(HMRedirectUrl)"
        
//       let url = "https://api.weibo.com/oauth2/authorize?client_id=1501561155&redirect_uri=http://www.baidu.com"
        //URL 确定要访问的资源
        guard let url = URL(string: urlString) else{
            return
        }
        //建立请求
        let request = URLRequest(url: url)
        
        //webView加载请求
        webView.loadRequest(request)

       
    }
    @objc fileprivate func close (){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    //MARK:自动填充监听方法 
    //webview的注入 只是用JS修改 本地浏览器的缓存内容
    //点击登录的时候 将本地数据上传给服务器
    @objc private func autoFill(){
        //准备js
        let js = "document.getElementById('userId').value = 'guo018@gmail.com';" + "document.getElementById('passwd').value = 'Freedom123';"
        
        //让webview 执行 js
        webView.stringByEvaluatingJavaScript(from: js)
        
    }

}
extension HMOAuthViewController:UIWebViewDelegate{
    //JS与webview互调 将要加载请求调用的方法
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        if request.url?.absoluteString.hasPrefix(HMRedirectUrl) == false{
            
            
            // print("加载请求----\(request.url?.absoluteString)")
            
            return true
        }
        //query 就是URL “？”后面的所有部分
        if request.url?.query?.hasPrefix("code=") == false {
            
            //print("加载请求----\(request.url?.query)")
            //取消授权
            close()
            
            return false
        }
       
        
        
        //query 中获取授权码
        //代码到了此处 URL 里面必定有查询的授权码 code
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        HMShareManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
                
            }else{
                //SVProgressHUD.showInfo(withStatus: "登录成功")
                //跳转页面 通过通知 不管是否有监听者
                //发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: HMUserLoginSuccessNotification), object: nil)
                
                //关闭
                self.close()
            }
        }
        
        print("获取授权码 \(code)")
        
        
        return false
    }
    //开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        //增加指示器
        SVProgressHUD.show()
    }
    //完成加载
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //取消指示器
        SVProgressHUD.dismiss()
    }
    
}
